package Homework;

import java.util.HashSet;
import java.util.Objects;

/**
 * @author DCSGO
 * @version 1.0
 */

@SuppressWarnings({"all"})
public class Homework05 {
    //已知: Person类按照id和name重写了hashCode和equals方法,问下面代码输出什么?
    public static void main(String[] args) {
        HashSet set = new HashSet();
        Person1 p1 = new Person1(1001, "AA");
        Person1 p2 = new Person1(1002, "BB");
        set.add(p1);
        set.add(p2);
        p1.name = "CC";//Set 中的 p1 确实是被修改了
        set.remove(p1);
        //删除失败 Person1(1001, "AA")--原来的
        //Person1(1001, "CC")--修改后的 hash 值不相同
        System.out.println(set);
        set.add(new Person1(1001, "CC"));
        //添加成功 接上面：由于p1 与新 new 的对象的 hash 值不同故不会发生碰撞
        System.out.println(set);
        set.add(new Person1(1001, "AA"));
        //添加成功 接上面：虽然新 new 的对象的 hash 值与原来的p1 相同发生了碰撞
        //但在 equals 时却不相等 于是便添加成功了
        System.out.println(set);


        //[Person1{id=1002, name='BB'}, Person1{id=1001, name='CC'}]
        //[Person1{id=1002, name='BB'}, Person1{id=1001, name='CC'}, Person1{id=1001, name='CC'}]
        //[Person1{id=1002, name='BB'}, Person1{id=1001, name='CC'}, Person1{id=1001, name='CC'}, Person1{id=1001, name='AA'}]

    }
}

class Person1 {
    int id;
    String name;

    public Person1(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person1 person = (Person1) o;
        return id == person.id && Objects.equals(name, person.name);
    }

    @Override
    public String toString() {
        return "Person1{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name);
    }
}
